# coding=utf8

import sys
import json
import random
import finder.fs as fs

from openpyxl.reader.excel import load_workbook

reload(sys)
sys.setdefaultencoding('utf-8')


def get_options(pairs):
    max_index = len(pairs) - 1
    options = []
    for i in range(0, 4):
        position = random.randint(0, max_index)
        translation = pairs[position]['translation']
        options.append(translation)
    return options


def process(work_book, course):
    word_sheet_name = "%s_word" % course
    wb = load_workbook(filename=work_book)
    ws = wb.get_sheet_by_name(word_sheet_name)

    pairs = []
    for r in range(2, ws.max_row + 1):
        word = str(ws.cell(row=r, column=2).value).strip()
        translation = str(ws.cell(row=r, column=4).value).strip()
        pair = dict()
        pair['translation'] = translation
        pair['word'] = word
        pairs.append(pair)

    quizzes = []
    for i in range(0, len(pairs)):
        pair = pairs[i]
        word = pair['word']
        translation = pair['translation']
        quiz = dict()
        quiz['id'] = i
        quiz['question'] = word
        quiz['options'] = get_options(pairs)
        position = random.randint(0, 3)
        quiz['answer'] = position
        quiz['options'][position] = translation
        quizzes.append(quiz)
    output = json.dumps(quizzes, ensure_ascii=False)
    home = fs.root_path()
    fs.write("%s/python/%s_quiz.json" % (home, course), output)
